CanReadData.php

<?php

namespace Phad\Test\Phad;

class CanReadData extends \Phad\Tester {

    /**
     * the active user role. Used in @see(can_read())
     */
    public $user = null;

    /**
     * The `user_has_role` hanler that `Phad` calls during `can_read_data()`
     */
    public function user_has_role($role){
        if ($this->user === null)return false;

        if ($this->user === $role) return true;
        return false;
    }

    /**
     * Set `$this->user = 'guest'` or `$this->user = 'admin'` (or whatever) to set the user role prior to calling `$this->can_read()`
     *
     * @test `$phad->can_read_data()`
     *
     * @param $expect true/false whether `$phad->can_read()` should be `true/false` 
     * @param $node array as generated from a data node
     * @param $msg a message to print with the test results
     * @param $ItemInfo
     */
    public function can_read(bool $expect, array $node, $msg, array $ItemInfo=[]){
        $phad2 = new \Phad();

        $phad2->handlers['user_has_role'] = [$this, 'user_has_role'];
        $ItemInfo = (object)$ItemInfo;
        $ItemInfo->mode = null;
        $can_read = $phad2->can_read_data($node, $ItemInfo);

        if ($expect==$can_read){
            $this->handleDidPass(true, false);
            echo "\nPass: ".$msg;
        } else {
            $this->handleDidPass(false, false);
            echo "\nFail: ".$msg;
        }
    }

    /**
     * @test `Phad->can_read_data`
     */
    public function testCanReadData(){

        $this->user = null;
        $this->can_read(true, ['type'=>'default'], 'default, no access');

        $this->user = 'guest';
        $this->can_read(false, ['type'=>'default', 'access'=>'role:admin'], 'default, !have role:admin');

        $this->user = 'admin';
        $this->can_read(true, ['type'=>'default', 'access'=>'role:admin'], 'default, has role:admin');
        
        $this->user = 'admin';
        $this->can_read(true, [], 'no type, no access');
    }



}